/*
 * @Description: 基本柱状图
 * @Author: YoungWind
 * @Date: 2020-09-20 19:22:50
 * @LastEditTime: 2020-09-29 21:28:10
 * @LastEditors: YoungWind
 * @FilePath: \ccd3\src\ccd3\flower\charts\flower.js
 */

import BaseChart from '../../BaseChart.js'
export default class Flower extends BaseChart {
  constructor(id, data) {
    super(id, data);
    this.flowerData = null;

    this.petalsNum = 5;
    this.factor = 1;
    this.flowerRadius = null;
    this.flowerWidth = 1;
    this.flowerAngle = Math.PI * 2;
    this.duration = 1000;

    this.color = d3.schemeCategory10;
  }

  setPetalsNum(val) {
    this.petalsNum = val;
    return this;
  }
  setFactor(val) {
    this.factor = val;
    return this;
  }
  setFlowerRadius(val) {
    this.flowerRadius = val;
    return this;
  }
  setFlowerWidth(val) {
    this.flowerWidth = val;
    return this;
  }
  setFlowerAngle(val) {
    this.flowerAngle = val;
    return this;
  }
  setDuration(val) {
    this.duration = val;
    return this;
  }


  init() {
    // 初始化画布
    this.initSvg();
    // 初始化主体内容
    this.initMainGroup();
    this.initFlowerGroup();
    this.initFlower();
    return this;
  }

  initFlowerGroup() {
    this.flowerGroup = this.mg.append('g').attr('transform', `translate(${this.innerWidth / 2},${this.innerHeight / 2})`);
  }

  initFlower() {
    if (!this.flowerRadius)
      this.flowerRadius = Math.min(this.innerHeight, this.innerWidth) / 2;
  }

  /**
   * @description: 更新
   * @param {type} 
   * @return {type} 
   */
  render(data) {
    if (data) {
      this.data = data;
    }
    this.renderData();
    this.renderFlower();
    return this;
  }

  renderFlower() {
    this.flowerGroup
      .selectAll('path')
      .data(this.flowerData)
      .join('path')
      .attr('fill', (d, i) => this.color[i])
      .transition()
      .duration(this.duration)
      .attrTween("d", (d) => {
        return (t) => {
          return this.petal(t * d.angle, t * d.radius, t * d.width);
        }
      })
  }

  renderData = () => {
    const petalsNum = this.petalsNum;
    const radius = this.flowerRadius;
    const width = this.flowerWidth;
    this.flowerData = [];
    for (let index = 0; index < petalsNum; index++) {
      this.flowerData.push({
        angle: index * (this.flowerAngle / petalsNum),
        radius,
        width
      })
    }
  }

  petal = (angle, radius, width) => {
    let [dx, dy] = [Math.cos(angle), Math.sin(angle)];
    let [nx, ny] = [-Math.sin(angle), Math.cos(angle)];
    let s = this.factor;
    return `M 0 0 
          Q ${dx * radius * s + nx * width / 2} ${dy * radius * s + ny * width / 2} ${dx * radius} ${dy * radius}
          Q ${dx * radius * s - nx * width / 2} ${dy * radius * s - ny * width / 2} 0 0 Z`
  }
}